package com.mimo.comet.config;

import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import com.mimo.common.listener.IMessage;

@Configuration
public class RedisPubSubConfig {

  private static final Logger log = LoggerFactory.getLogger(RedisPubSubConfig.class);

  // 初始化监听器
  @Bean
  RedisMessageListenerContainer container(@Qualifier("redisConnectionFactory") RedisConnectionFactory connectionFactory,
      @Autowired Collection<IMessage> listeners) {
    RedisMessageListenerContainer container = new RedisMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    for (IMessage listener : listeners) {
      Topic topic = new ChannelTopic(listener.getTopic());
      MessageListenerAdapter adapter = new MessageListenerAdapter(listener, "onMessage");
      adapter.afterPropertiesSet();
      container.addMessageListener(adapter, topic);
      log.info("Registered MessageListenerAdapter[{}]", listener.getClass().getSimpleName());
    }
    return container;
  }

}